package net.uiiang.android.alkaid;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import net.uiiang.android.alkaid.core.ListFile;
import net.uiiang.android.alkaid.helper.FileManagerDbAdapter;
import net.uiiang.android.alkaid.helper.Preferences;
import net.uiiang.android.alkaid.object.FileItem;
import net.uiiang.android.alkaid.utils.BitmapUtil;
import net.uiiang.android.alkaid.utils.FileUtils;
import net.uiiang.android.alkaid.utils.Utils;

import org.apache.commons.io.FilenameUtils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class FileManager extends ListFile {

    MediaPlayer mMediaPlayer = null;

    ImageButton playButton = null;
    ImageButton stopButton = null;
    private FileManagerDbAdapter fileManagerDbAdapter;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        super.onCreateOptionsMenu(menu);
        // 如果是内部调用,或外部调用使用preferences,启用此菜单
        if (insideAllMenuAvailable
                || Utils.contains(externalUseMenuItems,
                        Constant.OPTION_MENU_ITEM_PREFERENCES)) {
            menu.add(0, Constant.OPTION_MENU_ITEM_PREFERENCES, 0,
                    R.string.menu_setup).setIcon(
                    android.R.drawable.ic_menu_preferences);
        }
        // 如果是内部调用,或外部调用使用新建文件夹,启用此菜单
        if (insideAllMenuAvailable
                || Utils.contains(externalUseMenuItems,
                        Constant.OPTION_MENU_ITEM_NEW_DIRECTORY)) {
            menu.add(0, Constant.OPTION_MENU_ITEM_NEW_DIRECTORY, 1,
                    R.string.menu_new_directory).setIcon(
                    android.R.drawable.ic_menu_add);
        }
        // 如果是内部调用,或外部调用使用粘贴,启用此菜单
        if (insideAllMenuAvailable
                || Utils.contains(externalUseMenuItems,
                        Constant.OPTION_MENU_ITEM_PASTE)) {
            menu
                    .add(0, Constant.OPTION_MENU_ITEM_PASTE, 2,
                            R.string.menu_paste).setIcon(
                            android.R.drawable.star_big_off);
        }
        // 关于菜单
        menu.add(0, Constant.OPTION_MENU_ITEM_ABOUT, 99, R.string.menu_about);
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        fileManagerDbAdapter = new FileManagerDbAdapter(FileManager.this);
        fileManagerDbAdapter.open();
    }

    @Override
    protected void onPause() {
        super.onPause();
        fileManagerDbAdapter.close();
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
        case Constant.OPTION_MENU_ITEM_ABOUT: {
            Intent i = new Intent(this, About.class);
            startActivity(i);
            return true;
        }
        case Constant.OPTION_MENU_ITEM_PREFERENCES: {
            // Intent i = new Intent().setClass(this, Preferences.class);
            Intent i = new Intent(this, Preferences.class);
            startActivityForResult(i, Constant.ACTIVITY_PREFERENCES);
            return true;
        }
        case Constant.OPTION_MENU_ITEM_NEW_DIRECTORY: {
            createNewDirectory();
            return true;
        }
        case Constant.OPTION_MENU_ITEM_PASTE: {
            if (controlFile != null) {
                try {
                    final File f = new File(currentDirectory.getAbsolutePath()
                            + "/" + controlFile.getName());
                    if (controlFile.getAbsolutePath().equals(
                            f.getAbsolutePath())) {
                        new AlertDialog.Builder(FileManager.this).setMessage(
                                R.string.has_same_dir).setPositiveButton(
                                R.string.close,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        return;
                                    }
                                }).show();
                        return true;
                    }
                    if (f.exists()) {
                        new AlertDialog.Builder(FileManager.this).setMessage(
                                R.string.has_same_name_file).setPositiveButton(
                                R.string.btn_overlay,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        try {
                                            if (f.isFile()) {
                                                f.delete();
                                            }
                                            if (controlFile.isFile()) {
                                                org.apache.commons.io.FileUtils
                                                        .copyFile(
                                                                controlFile,
                                                                new File(
                                                                        currentDirectory
                                                                                .getAbsolutePath()
                                                                                + "/"
                                                                                + controlFile
                                                                                        .getName()));
                                            } else if (controlFile
                                                    .isDirectory()) {
                                                org.apache.commons.io.FileUtils
                                                        .copyDirectory(
                                                                controlFile,
                                                                new File(
                                                                        currentDirectory
                                                                                .getAbsolutePath()
                                                                                + "/"
                                                                                + controlFile
                                                                                        .getName()));
                                            }
                                            browseTo(currentDirectory);
                                            // new File(currentDirectory
                                            // .getAbsolutePath()
                                            // + "/" + controlFile.getName())
                                            // .delete();
                                            controlFile = null;
                                        } catch (IOException e) {
                                            controlFile = null;
                                            e.printStackTrace();
                                        }
                                    }
                                }).setNeutralButton(R.string.btn_cancel,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        return;
                                    }
                                }).show();
                    } else {
                        if (controlFile.isFile()) {
                            org.apache.commons.io.FileUtils.copyFile(
                                    controlFile, new File(currentDirectory
                                            .getAbsolutePath()
                                            + "/" + controlFile.getName()));
                        } else if (controlFile.isDirectory()) {
                            org.apache.commons.io.FileUtils.copyDirectory(
                                    controlFile, new File(currentDirectory
                                            .getAbsolutePath()
                                            + "/" + controlFile.getName()));
                        }
                        controlFile = null;
                        browseTo(currentDirectory);
                    }
                } catch (IOException e) {
                    controlFile = null;
                    e.printStackTrace();
                }
            } else {
                new AlertDialog.Builder(FileManager.this).setMessage(
                        R.string.unselect_copy_file).setNeutralButton(
                        R.string.btn_confirm,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                return;
                            }
                        }).show();
            }
            return true;
        }
        }

        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case Constant.DIALOG_CREATE_NEW_DIRECTORY: {
            LayoutInflater factory = LayoutInflater.from(this);
            final View textEntryView = factory.inflate(R.layout.new_directory,
                    null);

            return new AlertDialog.Builder(FileManager.this).setIcon(
                    android.R.drawable.ic_menu_add).setTitle(
                    R.string.menu_new_directory).setView(textEntryView)
                    .setPositiveButton(R.string.btn_confirm,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {
                                    String newDirectoryName = (String) ((EditText) textEntryView
                                            .findViewById(R.id.new_directory_name_edit))
                                            .getText().toString();
//                                    System.out.println("newDirectoryName"
//                                            + newDirectoryName);
                                    if (!TextUtils.isEmpty(newDirectoryName)) {
                                        File newFile = new File(
                                                currentDirectory
                                                        .getAbsolutePath()
                                                        + "/"
                                                        + newDirectoryName);
//                                        System.out.println("!newFile.exists()"
//                                                + !newFile.exists());
                                        if (!newFile.exists()) {
                                            newFile.mkdir();
                                            browseTo(currentDirectory);
                                        }
                                    }
                                }
                            }).setNegativeButton(R.string.btn_cancel,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {
                                    return;
                                }
                            }).create();
        }
        case Constant.DIALOG_DELETE_FILE: {
            return new AlertDialog.Builder(FileManager.this).setIcon(
                    android.R.drawable.ic_dialog_alert).setTitle(
                    R.string.delete_file_alert_title).setMessage(
                    R.string.delete_file_alert_msg).setPositiveButton(
                    R.string.btn_confirm,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            deleteFile();
                        }
                    }).setNegativeButton(R.string.btn_cancel,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            return;
                        }
                    }).create();
        }
        case Constant.DIALOG_DELETE_DIRECTORY: {
            return new AlertDialog.Builder(FileManager.this).setIcon(
                    android.R.drawable.ic_dialog_alert).setTitle(
                    R.string.delete_directory_alert_title).setMessage(
                    R.string.delete_directory_alert_msg).setPositiveButton(
                    R.string.btn_confirm,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            deleteFile();
                        }
                    }).setNegativeButton(R.string.btn_cancel,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            return;
                        }
                    }).create();
        }
        }
        return null;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {

        AdapterView.AdapterContextMenuInfo info;
        try {
            info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        } catch (ClassCastException e) {
            return;
        }
        // FileView fv =
        // (FileView)this.getListView().getItemAtPosition(info.position);
        FileItem fileItem = this.directoryEntries.get(info.position);
        String selectedFileString = fileItem.getTitle();
        if (!selectedFileString.equals("..")) {
            super.onCreateContextMenu(menu, v, menuInfo);
            menu.setHeaderTitle(selectedFileString);

            if (Utils.contains(externalUseMenuItems,
                    Constant.CONTEXT_MENU_ITEM_SELECT)) {
                // 选择
                menu.add(0, Constant.CONTEXT_MENU_ITEM_SELECT, 0,
                        R.string.menu_select);
            }

            if (insideAllMenuAvailable
                    || Utils.contains(externalUseMenuItems,
                            Constant.CONTEXT_MENU_ITEM_OPEN)) {
                if (Constant.FILE_TYPE_DIRECTORY.equals(this.directoryEntries
                        .get(info.position).getFileType())) {
                    // 打开
                    menu.add(0, Constant.CONTEXT_MENU_ITEM_OPEN, 0,
                            R.string.menu_open).setIcon(
                            android.R.drawable.ic_menu_search);
                }
            }
            if (insideAllMenuAvailable
                    || Utils.contains(externalUseMenuItems,
                            Constant.CONTEXT_MENU_ITEM_DELETE)) {
                // 删除
                menu.add(0, Constant.CONTEXT_MENU_ITEM_DELETE, 1,
                        R.string.menu_delete).setIcon(
                        android.R.drawable.ic_menu_delete);
            }
            if (insideAllMenuAvailable
                    || Utils.contains(externalUseMenuItems,
                            Constant.CONTEXT_MENU_ITEM_VIEW_INFO)) {
                // 重命名
                // menu.add(0, Constant.MENU_ITEM_RENAME, 2,
                // R.string.menu_rename);
                // 查看详情
                menu.add(0, Constant.CONTEXT_MENU_ITEM_VIEW_INFO, 3,
                        R.string.view_info).setIcon(
                        android.R.drawable.ic_menu_info_details);
            }
            if (insideAllMenuAvailable
                    || Utils.contains(externalUseMenuItems,
                            Constant.CONTEXT_MENU_ITEM_COPY_TO)) {
                // 复制
                menu.add(0, Constant.CONTEXT_MENU_ITEM_COPY_TO, 4,
                        R.string.menu_copy_to).setIcon(
                        android.R.drawable.ic_menu_info_details);
            }
            if (insideAllMenuAvailable && !fileItem.isFileFavorite()) {
                menu.add(0, Constant.CONTEXT_MENU_ITEM_ADD_TO_FAVORITE, 5,
                        R.string.menu_add_favorite);
            }
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        controlFile = null;
        AdapterView.AdapterContextMenuInfo info;
        try {
            info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        } catch (ClassCastException e) {
            return false;
        }
        if (info != null) {
            String selectedFileString = this.directoryEntries
                    .get(info.position).getTitle();
            File thisFile = new File(this.currentDirectory.getAbsolutePath()
                    + "/"
                    + selectedFileString
                    + this.directoryEntries.get(info.position)
                            .getFileExtension());
            if (thisFile.exists()) {
                switch (item.getItemId()) {
                case Constant.CONTEXT_MENU_ITEM_SELECT: {
                    Intent intent = new Intent();
                    // intent.setAction(mUri.toString());
                    if (!externalMutipleSelect) {
                        intent.putExtra("selected_uri", new String[] { thisFile
                                .getAbsolutePath() });
                    } else {
                        ArrayList<FileItem> fileItems = this.directoryEntries;

                        ArrayList<String> tmpArrList = new ArrayList<String>();
                        for (FileItem fileItem : fileItems) {
                            if (fileItem.isChecked()) {
                                tmpArrList.add((this.currentDirectory
                                        .getAbsolutePath().equals("/") ? "/"
                                        : this.currentDirectory + "/")
                                        + fileItem.getTitle()+fileItem.getFileExtension());
                            }
                        }
                        String[] checkedArray = new String[tmpArrList.size()];
                        for (int i = 0; i < tmpArrList.size(); i++) {
                            checkedArray[i] = tmpArrList.get(i);
                        }
                        intent.putExtra("selected_uri", checkedArray);
                    }
                    setResult(RESULT_OK, intent);
                    finish();
                    return true;
                }
                case Constant.CONTEXT_MENU_ITEM_DELETE: {
                    if (thisFile.isDirectory()) {
                        controlFile = thisFile;
                        showDialog(Constant.DIALOG_DELETE_DIRECTORY);

                    } else if (thisFile.isFile()) {
                        controlFile = thisFile;
                        showDialog(Constant.DIALOG_DELETE_FILE);
                    }
                    return true;
                }
                case Constant.CONTEXT_MENU_ITEM_OPEN: {
                    if (thisFile.isDirectory()) {
                        browseTo(thisFile);
                    }
                    return true;
                }
                case Constant.CONTEXT_MENU_ITEM_VIEW_INFO: {
                    controlFile = thisFile;
                    if (thisFile.isDirectory()) {
                        FileUtils fileUtils = new FileUtils();
                        fileUtils.getDirectoyInfo(controlFile);
                        LayoutInflater factory = LayoutInflater.from(this);
                        final View directoryInfoView = factory.inflate(
                                R.layout.directory_info_view, null);
                        // ((TextView)directoryInfoView.findViewById(R.id.id_vi_sub_directory_value)).setText(fileUtils.getSubDirectorySize());
                        // ((TextView)directoryInfoView.findViewById(R.id.id_view_info_file_size_value)).setText(fileUtils.getSubFileSize());
                        ((TextView) directoryInfoView
                                .findViewById(R.id.id_view_info_date_value))
                                .setText(fileUtils.getFileDateStr());
                        ((TextView) directoryInfoView
                                .findViewById(R.id.id_view_info_name_value))
                                .setText(controlFile.getName());
                        ((TextView) directoryInfoView
                                .findViewById(R.id.id_view_info_size_value))
                                .setText(fileUtils.getFileSizeString());
                        ((TextView) directoryInfoView
                                .findViewById(R.id.id_view_info_time_value))
                                .setText(fileUtils.getFileTimeStr());
                        directoryInfoView.setMinimumWidth(300);
                        // dialog.setContentView(directoryInfoView);
                        new AlertDialog.Builder(FileManager.this).setView(
                                directoryInfoView).setPositiveButton(
                                R.string.btn_confirm,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        return;
                                    }
                                }).show().setOnCancelListener(
                                new OnCancelListener() {

                                    public void onCancel(DialogInterface dialog) {
//                                        System.out
//                                                .println("setOnCancelListener");
                                        controlFile = null;
                                    }
                                });

                    } else {
                        FileUtils fileUtils = new FileUtils();
                        fileUtils.getFileInfo(controlFile);
                        LayoutInflater factory = LayoutInflater.from(this);
                        final View fileInfoView = factory.inflate(
                                R.layout.file_info_view, null);
                        ((TextView) fileInfoView
                                .findViewById(R.id.id_view_info_date_value))
                                .setText(fileUtils.getFileDateStr());
                        ((TextView) fileInfoView
                                .findViewById(R.id.id_view_info_name_value))
                                .setText(controlFile.getName());
                        ((TextView) fileInfoView
                                .findViewById(R.id.id_view_info_size_value))
                                .setText(fileUtils.getFileSizeString());
                        ((TextView) fileInfoView
                                .findViewById(R.id.id_view_info_time_value))
                                .setText(fileUtils.getFileTimeStr());
                        ((TextView) fileInfoView
                                .findViewById(R.id.id_view_info_type_value))
                                .setText(fileUtils.getFileExtension());
                        fileInfoView.setMinimumWidth(400);
                        new AlertDialog.Builder(FileManager.this).setView(
                                fileInfoView).setPositiveButton(
                                R.string.btn_confirm,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        return;
                                    }
                                }).show().setOnCancelListener(
                                new OnCancelListener() {

                                    public void onCancel(DialogInterface dialog) {
                                        controlFile = null;
                                    }
                                });
                    }
                    controlFile = null;
                    return true;
                }
                case Constant.CONTEXT_MENU_ITEM_COPY_TO: {
                    controlFile = thisFile;
                    return true;
                }
                case Constant.CONTEXT_MENU_ITEM_ADD_TO_FAVORITE: {
                    controlFile = thisFile;
                    LayoutInflater factory = LayoutInflater.from(this);
                    final View textEntryView = factory.inflate(
                            R.layout.new_directory, null);

                    TextView tv = ((TextView) textEntryView
                            .findViewById(R.id.new_directory_name_view));
                    tv.setText(R.string.inputAliasName);
                    final EditText editText = ((EditText) textEntryView
                            .findViewById(R.id.new_directory_name_edit));
                    final String fileType;
                    if (FileUtils.isDirectory(controlFile)) {
                        fileType = Constant.FILE_TYPE_DIRECTORY;
                        editText.setText(controlFile.getName());
                    } else {
                        fileType = Constant.FILE_TYPE_FILE;
                        editText.setText(FilenameUtils
                                .removeExtension(controlFile.getName()));
                    }
//                    editText.setMaxLines(1);
                    editText.setSingleLine(true);
                    editText.selectAll();
                    new AlertDialog.Builder(FileManager.this).setIcon(
                            android.R.drawable.ic_menu_add).setTitle(
                            R.string.menu_add_favorite).setView(textEntryView)
                            .setPositiveButton(R.string.btn_confirm,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialog,
                                                int whichButton) {
                                            String aliasName = (String) ((EditText) textEntryView
                                                    .findViewById(R.id.new_directory_name_edit))
                                                    .getText().toString();
                                            fileManagerDbAdapter
                                                    .createFavorite(controlFile
                                                            .getAbsolutePath(),
                                                            controlFile
                                                                    .getName(),
                                                            aliasName, fileType);
                                            controlFile = null;
                                            BrowseFileTab.tabHost
                                                    .setCurrentTab(Constant.TAB_FAVORITE_INDEX);
                                        }
                                    }).setNegativeButton(R.string.btn_cancel,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialog,
                                                int whichButton) {
                                            controlFile = null;
                                            return;
                                        }
                                    }).show().setOnCancelListener(
                                    new OnCancelListener() {

                                        public void onCancel(
                                                DialogInterface dialog) {
//                                            System.out
//                                                    .println("setOnCancelListener");
                                            controlFile = null;
                                        }
                                    });
                    // controlFile = null;
                    return true;
                }
                }
            }
        }
        return false;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
                mMediaPlayer.release();
            }

            if (FileUtils.isDirectory(this.externalRootDirectory)
                    && !this.externalRootDirectory.getAbsolutePath().equals(
                            currentDirectory.getAbsolutePath())) {
                this.upOneLevel();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void setAnimation() {
        AnimationSet set = new AnimationSet(true);

        Animation animation = new AlphaAnimation(0.0f, 1.0f);
        animation.setDuration(50);
        set.addAnimation(animation);

        animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        animation.setDuration(100);
        set.addAnimation(animation);

        LayoutAnimationController controller = new LayoutAnimationController(
                set, 0.5f);

        ListView listView = getListView();
        listView.setLayoutAnimation(controller);
    }

    @Override
    protected void openFile(File aDirectory) {
//        System.out.println("openfile " + aDirectory.getName());

        if (externalUseSimpleView) {
            super.openFile(aDirectory);
            // Intent intent = new Intent(Intent.ACTION_VIEW);
            if (FileUtils.checkEndsWithInStringArray(aDirectory.getName(),
                    getResources().getStringArray(R.array.fileEndingImage))) {
                viewImage(aDirectory);
            } else if (FileUtils.checkEndsWithInStringArray(aDirectory
                    .getName(), getResources().getStringArray(
                    R.array.fileEndingWebText))) {
                // intent.setType("text/*");
                // startActivity(Intent
                // .createChooser(intent, aDirectory.getName()));
            } else if (FileUtils.checkEndsWithInStringArray(aDirectory
                    .getName(), getResources().getStringArray(
                    R.array.fileEndingAudio))) {
                playAudio(aDirectory);
            } else if (FileUtils.checkEndsWithInStringArray(aDirectory
                    .getName(), getResources().getStringArray(
                    R.array.fileEndingVideo))) {
                // Uri uri = Uri.parse("file://" +
                // aDirectory.getAbsolutePath());
                // MediaPlayer mMediaPlayer = null;
                // try {
                // if (mMediaPlayer != null) {
                // mMediaPlayer.stop();
                // mMediaPlayer.release();
                // }
                // mMediaPlayer = MediaPlayer.create(this, uri);
                // if (mMediaPlayer != null) {
                // mMediaPlayer.start();
                // }
                // } catch (IllegalArgumentException e) {
                // e.printStackTrace();
                // } catch (IllegalStateException e) {
                // e.printStackTrace();
                // }
            } else if (FileUtils.checkEndsWithInStringArray(aDirectory
                    .getName(), getResources().getStringArray(
                    R.array.fileEndingText))) {
                // intent.setType("text/*");
                // startActivity(Intent
                // .createChooser(intent, aDirectory.getName()));
            } else if (FileUtils.checkEndsWithInStringArray(aDirectory
                    .getName(), getResources().getStringArray(
                    R.array.fileEndingApk))) {
                installApk(aDirectory);
            }
        }
    }

    // public void browseTo(final File aDirectory) {
    // browseTo(aDirectory);
    // }

    private void installApk(File file) {
        final File apkFile = file;
        new AlertDialog.Builder(FileManager.this).setTitle(file.getName())
                .setMessage(getResources().getString(R.string.installApkInfo))
                .setPositiveButton(R.string.installApk,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {

                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent
                                        .setDataAndType(Uri.fromFile(apkFile),
                                                "application/vnd.android.package-archive");
                                startActivity(intent);
                                return;
                            }
                        }).setNegativeButton(R.string.btn_cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                return;
                            }
                        }).show();

    }

    private void viewImage(File aDirectory) {
        LayoutInflater factory = LayoutInflater.from(this);
        View simpleImageView = factory
                .inflate(R.layout.simple_image_view, null);
        ImageView imageView = (ImageView) simpleImageView
                .findViewById(R.id.simple_image_view_src);
        // Bitmap.createScaledBitmap(BitmapFactory.decodeFile(filepath),100,
        // 100, true);

        Bitmap bm;
        try {
            bm = BitmapUtil.getBitmap(this, aDirectory.getAbsolutePath());
            
            imageView.setImageBitmap(bm);
            new AlertDialog.Builder(FileManager.this).setView(simpleImageView)
                    .setTitle(
                            aDirectory.getName()
                                    + " "
                                    + getResources()
                                            .getString(R.string.preview))
                    .setPositiveButton(R.string.close,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    return;
                                }
                            }).show();

            imageView = null;
            bm = null;
            simpleImageView = null;
            factory = null;
            System.gc();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void playAudio(File aDirectory) {
        LayoutInflater factory = LayoutInflater.from(this);
        View simpleAudioView = factory
                .inflate(R.layout.simple_audio_view, null);
        final String filePath = aDirectory.getAbsolutePath();
        playButton = (ImageButton) simpleAudioView
                .findViewById(R.id.play_button);
        stopButton = (ImageButton) simpleAudioView
                .findViewById(R.id.stop_button);

        playButton.setOnClickListener(new OnClickListener() {
            Uri uri = Uri.parse("file://" + filePath);

            public void onClick(View v) {
                if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                    mMediaPlayer.stop();
                    mMediaPlayer.release();
                }
                mMediaPlayer = null;
                mMediaPlayer = MediaPlayer.create(FileManager.this, uri);
                if (mMediaPlayer != null) {
                    mMediaPlayer.start();
                }
                v.setClickable(false);
                stopButton.setClickable(true);
            }
        });

        stopButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                    mMediaPlayer.stop();
                    mMediaPlayer.release();
                }
                mMediaPlayer = null;
                playButton.setClickable(true);
                v.setClickable(false);
            }
        });
        new AlertDialog.Builder(FileManager.this).setView(simpleAudioView)
                .setTitle(
                        aDirectory.getName() + " "
                                + getResources().getString(R.string.preview))
                .setPositiveButton(R.string.close,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                if (mMediaPlayer != null
                                        && mMediaPlayer.isPlaying()) {
                                    mMediaPlayer.stop();
                                    mMediaPlayer.release();
                                }
                                mMediaPlayer = null;
                                return;
                            }
                        }).show();
    }

    protected void updatePreferences() {
        SharedPreferences sharedPref = PreferenceManager
                .getDefaultSharedPreferences(this);
        insideShowInfoInList = sharedPref.getBoolean(
                Preferences.KEY_SHOW_DIR_INFO, true);
        insideShowFileExtension = sharedPref.getBoolean(
                Preferences.KEY_SHOW_FILE_EXTENSION, true);

        insideAnimationList = sharedPref.getBoolean(
                Preferences.KEY_ANIMATION_LIST, true);

    }

    private void createNewDirectory() {
        showDialog(Constant.DIALOG_CREATE_NEW_DIRECTORY);
    }
}
